package com.example.testblue_b;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;

import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;

public class QrCodeActivity extends FragmentActivity implements DecoratedBarcodeView.TorchListener {
    ImageView iv_switch;
    DecoratedBarcodeView mDBV;
    private CaptureManager captureManager;
    private boolean isLightOn = false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_qrcode);
        mDBV = findViewById(R.id.dbv_custom);
        iv_switch = findViewById(R.id.btn_switch);
        iv_switch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                swichLight();
            }
        });
        initData(savedInstanceState);
    }

    private void initData(Bundle savedInstanceState) {
        // 如果没有闪光灯功能，就去掉相关按钮
        if(!hasFlash()) {
            iv_switch.setVisibility(View.GONE);
        }

        mDBV.setTorchListener(this);
        //重要代码，初始化捕获
        captureManager = new CaptureManager(this,mDBV);
        captureManager.initializeFromIntent(getIntent(),savedInstanceState);
        captureManager.decode();
    }

    // 判断是否有闪光灯功能
    private boolean hasFlash() {
        return getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }

    // 点击切换闪光灯
    public void swichLight(){
        if(isLightOn){
            mDBV.setTorchOff();
        }else{
            mDBV.setTorchOn();

        }
    }

    // torch 手电筒
    @Override
    public void onTorchOn() {
        isLightOn = true;
        iv_switch.setImageResource(R.mipmap.code_scan_btn_flash_down);
    }

    @Override
    public void onTorchOff() {
        isLightOn = false;
        iv_switch.setImageResource(R.mipmap.code_scan_btn_flash_nor);
    }

    @Override
    protected void onPause() {
        super.onPause();
        captureManager.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        captureManager.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        captureManager.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        captureManager.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return mDBV.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
    }
}
